import React, { useState } from 'react';
import { Row,Col, Menu, Card, Form, Input, Upload, Button, Avatar, Switch, List, message, Tabs, Divider, Radio } from 'antd';
import { createStyles } from 'antd-style';
import {
  UserOutlined,
  MailOutlined,
  PhoneOutlined,
  LockOutlined,
  KeyOutlined,
  SafetyOutlined,
  GithubOutlined,
  WechatOutlined,
  QqOutlined,
  AlipayOutlined,
  DingdingOutlined,
  UploadOutlined,
  BellOutlined,
  SettingOutlined,
  PlusOutlined,
  EnvironmentOutlined,
} from '@ant-design/icons';
import type { UploadFile } from 'antd/es/upload/interface';
import type { MenuProps } from 'antd';

const { TabPane } = Tabs;

const useStyles = createStyles(({ token }) => ({
  pageContainer: {
    padding: '24px',
    backgroundColor: token.colorBgLayout,
    minHeight: 'calc(100vh - 48px)',
  },
  settingsCard: {
    borderRadius: '12px',
    overflow: 'hidden',
    boxShadow: '0 4px 12px rgba(0, 0, 0, 0.05)',
  },
  menuSider: {
    width: '224px',
    borderRight: `1px solid ${token.colorBorderSecondary}`,
    marginRight: '24px',
    '& .ant-menu': {
      border: 'none',
    },
  },
  contentArea: {
    flex: 1,
    overflow: 'hidden',
  },
  formItem: {
    marginBottom: '24px',
  },
  avatarUploader: {
    width: '144px',
    height: '144px',
    marginBottom: '12px',
    '& .ant-upload': {
      width: '100%',
      height: '100%',
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center',
      background: token.colorBgContainer,
      border: `1px dashed ${token.colorBorder}`,
      borderRadius: '50%',
      cursor: 'pointer',
      transition: 'all 0.3s',
      '&:hover': {
        borderColor: token.colorPrimary,
      },
    },
  },
  avatar: {
    width: '100%',
    height: '100%',
    borderRadius: '50%',
  },
  uploadText: {
    marginTop: '8px',
    color: token.colorTextSecondary,
    textAlign: 'center',
  },
  bindItem: {
    display: 'flex',
    alignItems: 'center',
    padding: '16px 0',
    borderBottom: `1px solid ${token.colorBorderSecondary}`,
    '&:last-child': {
      borderBottom: 'none',
    },
  },
  bindIcon: {
    fontSize: '24px',
    marginRight: '16px',
    color: token.colorTextSecondary,
  },
  bindContent: {
    flex: 1,
  },
  bindTitle: {
    fontWeight: 'bold',
    marginBottom: '4px',
  },
  bindDesc: {
    color: token.colorTextSecondary,
    fontSize: '12px',
  },
  notificationItem: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    padding: '16px 0',
    borderBottom: `1px solid ${token.colorBorderSecondary}`,
    '&:last-child': {
      borderBottom: 'none',
    },
  },
  notificationContent: {
    flex: 1,
  },
  notificationTitle: {
    fontWeight: 'bold',
    marginBottom: '4px',
  },
  notificationDesc: {
    color: token.colorTextSecondary,
    fontSize: '12px',
  },
  formLabel: {
    fontWeight: 'bold',
  },
  sectionTitle: {
    fontWeight: 'bold',
    fontSize: '16px',
    marginBottom: '16px',
  },
}));

type MenuItem = Required<MenuProps>['items'][number];

const getItem = (
  label: React.ReactNode,
  key: React.Key,
  icon?: React.ReactNode,
  children?: MenuItem[],
): MenuItem => {
  return {
    key,
    icon,
    children,
    label,
  } as MenuItem;
};

const UserSettings: React.FC = () => {
  const { styles } = useStyles();
  const [selectedKey, setSelectedKey] = useState('basic');
  const [avatarUrl, setAvatarUrl] = useState<string>('https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png');
  const [fileList, setFileList] = useState<UploadFile[]>([]);

  // 菜单项
  const menuItems: MenuItem[] = [
    getItem('基本设置', 'basic', <UserOutlined />),
    getItem('安全设置', 'security', <SafetyOutlined />),
    getItem('账号绑定', 'binding', <LockOutlined />),
    getItem('新消息通知', 'notification', <BellOutlined />),
  ];

  // 处理菜单选择
  const handleMenuSelect = ({ key }: { key: string }) => {
    setSelectedKey(key);
  };

  // 处理头像上传
  const handleAvatarChange = (info: any) => {
    if (info.file.status === 'uploading') {
      return;
    }
    if (info.file.status === 'done') {
      // 模拟上传成功后获取图片URL
      setAvatarUrl(URL.createObjectURL(info.file.originFileObj));
      message.success('头像上传成功');
    }
  };

  // 处理表单提交
  const handleSubmit = () => {
    message.success('保存成功');
  };

  // 处理账号绑定
  const handleBind = (type: string) => {
    message.info(`绑定${type}账号`);
  };

  // 处理账号解绑
  const handleUnbind = (type: string) => {
    message.success(`解绑${type}账号成功`);
  };

  // 基本设置内容
  const renderBasicSettings = () => (
    <div>
      <h2 className={styles.sectionTitle}>基本设置</h2>
      <Form layout="vertical" onFinish={handleSubmit}>
        <Row gutter={24}>
          <Col span={16}>
            <Form.Item
              label={<span className={styles.formLabel}>邮箱</span>}
              name="email"
              rules={[{ required: true, message: '请输入邮箱' }]}
              initialValue="wangxiaoming@example.com"
            >
              <Input prefix={<MailOutlined />} placeholder="邮箱" />
            </Form.Item>

            <Form.Item
              label={<span className={styles.formLabel}>昵称</span>}
              name="nickname"
              rules={[{ required: true, message: '请输入昵称' }]}
              initialValue="王小明"
            >
              <Input prefix={<UserOutlined />} placeholder="昵称" />
            </Form.Item>

            <Form.Item
              label={<span className={styles.formLabel}>个人简介</span>}
              name="bio"
              initialValue="热爱编程与设计，专注于用户体验与前端性能优化，喜欢尝试新技术，乐于分享。"
            >
              <Input.TextArea rows={4} placeholder="个人简介" />
            </Form.Item>

            <Form.Item
              label={<span className={styles.formLabel}>所在地区</span>}
              name="location"
              initialValue="杭州市"
            >
              <Input prefix={<EnvironmentOutlined />} placeholder="所在地区" />
            </Form.Item>

            <Form.Item
              label={<span className={styles.formLabel}>联系电话</span>}
              name="phone"
              initialValue="138****6666"
            >
              <Input prefix={<PhoneOutlined />} placeholder="联系电话" />
            </Form.Item>

            <Form.Item>
              <Button type="primary" htmlType="submit">
                更新基本信息
              </Button>
            </Form.Item>
          </Col>
          <Col span={8} style={{ textAlign: 'center' }}>
            <Form.Item label={<span className={styles.formLabel}>头像</span>}>
              <div className={styles.avatarUploader}>
                <Upload
                  name="avatar"
                  listType="picture-card"
                  showUploadList={false}
                  beforeUpload={(file) => {
                    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
                    if (!isJpgOrPng) {
                      message.error('只能上传JPG/PNG格式的图片！');
                    }
                    const isLt2M = file.size / 1024 / 1024 < 2;
                    if (!isLt2M) {
                      message.error('图片大小不能超过2MB！');
                    }
                    return isJpgOrPng && isLt2M;
                  }}
                  onChange={handleAvatarChange}
                >
                  {avatarUrl ? (
                    <img src={avatarUrl} alt="avatar" className={styles.avatar} />
                  ) : (
                    <div>
                      <PlusOutlined />
                      <div className={styles.uploadText}>上传头像</div>
                    </div>
                  )}
                </Upload>
              </div>
              <div className={styles.uploadText}>支持 JPG、PNG 格式，文件小于 2MB</div>
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </div>
  );

  // 安全设置内容
  const renderSecuritySettings = () => (
    <div>
      <h2 className={styles.sectionTitle}>安全设置</h2>
      <List
        itemLayout="horizontal"
        dataSource={[
          {
            title: '账户密码',
            description: '当前密码强度：强',
            actions: [<a key="change">修改</a>],
            icon: <LockOutlined />,
          },
          {
            title: '密保手机',
            description: '已绑定手机：138****6666',
            actions: [<a key="change">修改</a>],
            icon: <PhoneOutlined />,
          },
          {
            title: '密保问题',
            description: '未设置密保问题，密保问题可有效保护账户安全',
            actions: [<a key="set">设置</a>],
            icon: <SafetyOutlined />,
          },
          {
            title: 'MFA 设备',
            description: '未绑定 MFA 设备，绑定后，可以进行二次确认',
            actions: [<a key="bind">绑定</a>],
            icon: <KeyOutlined />,
          },
        ]}
        renderItem={(item) => (
          <List.Item actions={item.actions}>
            <List.Item.Meta
              avatar={<div className={styles.bindIcon}>{item.icon}</div>}
              title={<div className={styles.bindTitle}>{item.title}</div>}
              description={<div className={styles.bindDesc}>{item.description}</div>}
            />
          </List.Item>
        )}
      />
    </div>
  );

  // 账号绑定内容
  const renderBindingSettings = () => (
    <div>
      <h2 className={styles.sectionTitle}>账号绑定</h2>
      <List
        itemLayout="horizontal"
        dataSource={[
          {
            title: '绑定淘宝',
            description: '当前未绑定淘宝账号',
            icon: <AlipayOutlined style={{ color: '#1677ff' }} />,
            bound: false,
            type: '淘宝',
          },
          {
            title: '绑定微信',
            description: '当前未绑定微信账号',
            icon: <WechatOutlined style={{ color: '#52c41a' }} />,
            bound: false,
            type: '微信',
          },
          {
            title: '绑定钉钉',
            description: '当前未绑定钉钉账号',
            icon: <DingdingOutlined style={{ color: '#1890ff' }} />,
            bound: false,
            type: '钉钉',
          },
          {
            title: '绑定Github',
            description: '已绑定Github账号：xiaoming',
            icon: <GithubOutlined />,
            bound: true,
            type: 'Github',
          },
        ]}
        renderItem={(item) => (
          <div className={styles.bindItem}>
            <div className={styles.bindIcon}>{item.icon}</div>
            <div className={styles.bindContent}>
              <div className={styles.bindTitle}>{item.title}</div>
              <div className={styles.bindDesc}>{item.description}</div>
            </div>
            {item.bound ? (
              <Button danger onClick={() => handleUnbind(item.type)}>
                解绑
              </Button>
            ) : (
              <Button type="primary" ghost onClick={() => handleBind(item.type)}>
                绑定
              </Button>
            )}
          </div>
        )}
      />
    </div>
  );

  // 新消息通知内容
  const renderNotificationSettings = () => (
    <div>
      <h2 className={styles.sectionTitle}>新消息通知</h2>
      <List
        itemLayout="horizontal"
        dataSource={[
          {
            title: '系统消息',
            description: '系统消息将以站内信的形式通知',
          },
          {
            title: '待办任务',
            description: '待办任务将以站内信的形式通知',
          },
          {
            title: '消息提醒',
            description: '消息提醒将以弹窗的形式通知',
          },
        ]}
        renderItem={(item) => (
          <div className={styles.notificationItem}>
            <div className={styles.notificationContent}>
              <div className={styles.notificationTitle}>{item.title}</div>
              <div className={styles.notificationDesc}>{item.description}</div>
            </div>
            <div>
              <Form.Item noStyle>
                <Switch defaultChecked />
              </Form.Item>
            </div>
          </div>
        )}
      />
      <Divider />
      <Form layout="vertical">
        <Form.Item
          label={<span className={styles.formLabel}>消息通知方式</span>}
          name="notificationType"
          initialValue="site"
        >
          <Radio.Group>
            <Radio value="site">站内信通知</Radio>
            <Radio value="email">邮件通知</Radio>
            <Radio value="sms">短信通知</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item>
          <Button type="primary" onClick={handleSubmit}>
            保存设置
          </Button>
        </Form.Item>
      </Form>
    </div>
  );

  // 根据选中的菜单项渲染对应的内容
  const renderContent = () => {
    switch (selectedKey) {
      case 'basic':
        return renderBasicSettings();
      case 'security':
        return renderSecuritySettings();
      case 'binding':
        return renderBindingSettings();
      case 'notification':
        return renderNotificationSettings();
      default:
        return renderBasicSettings();
    }
  };

  return (
    <div className={styles.pageContainer}>
      <Card className={styles.settingsCard} bordered={false}>
        <div style={{ display: 'flex' }}>
          <div className={styles.menuSider}>
            <Menu
              mode="inline"
              selectedKeys={[selectedKey]}
              items={menuItems}
              onClick={handleMenuSelect}
              style={{ height: '100%' }}
            />
          </div>
          <div className={styles.contentArea}>{renderContent()}</div>
        </div>
      </Card>
    </div>
  );
};

export default UserSettings;
